from flask import Blueprint, request, render_template, g, jsonify
from exts import db
from models import DMenu as Dtable
admin_menu = Blueprint('menu',__name__,url_prefix='/menu')

@admin_menu.route('/index')
def index():
    where=[]
    where.append(Dtable.pid==0)
    key = request.args.get('key', '')
    if(key!=''):
        where.append(Dtable.name.like("%"+key+"%"))
    list = Dtable.query.filter(*where).order_by(Dtable.pid.asc(),Dtable.sort.asc(),Dtable.id.desc()).all()

    my_list=[]
    for val in list:
        my_list.append(val)
        vlist=Dtable.query.filter(Dtable.pid==val.id).order_by(Dtable.pid.asc(),Dtable.sort.asc(),Dtable.id.desc()).all()
        for v in vlist:
            my_list.append(v)

    data={
        'keys':{'key':key},
        'data':my_list
    }
    return render_template('admin/menu/index.html',**data)

@admin_menu.route('/icon')
def icon():
    return render_template('admin/menu/icon.html')
@admin_menu.route('/add')
def add():
    menu_list=Dtable.query.filter(Dtable.pid==0).order_by(Dtable.sort.asc(),Dtable.id.desc()).all()
    return render_template('admin/menu/edit.html',info=None,menu_list=menu_list)

@admin_menu.route('/edit')
def edit():
    id = request.args.get('id', '0')
    info = Dtable.query.filter(Dtable.id == id).first()
    menu_list = Dtable.query.filter(Dtable.pid == 0).order_by(Dtable.sort.asc(), Dtable.id.desc()).all()
    return render_template('admin/menu/edit.html',info=info,menu_list=menu_list)

@admin_menu.route('/save',methods=['POST'])
def save():
    post = request.form.to_dict()
    if post['id']=='0':
        post.pop('id')
        adddb = Dtable(**post)
        db.session.add(adddb)
        db.session.commit()
    else:
        Dtable.query.filter(Dtable.id == post['id']).update(post)
        db.session.commit()

    return jsonify({'code': 200, 'msg': "保存成功!"})


@admin_menu.route('/dellete')
def delete():
    id = int(request.args.get('id', 0))
    if id <7 :
        return jsonify({'code': 500, 'msg': "这几个禁止删除!"})
    Dtable.query.filter(Dtable.id == id).delete()
    db.session.commit()
    return jsonify({'code': 200, 'msg': "删除成功!"})

@admin_menu.route('/status')
def status():
    id = int(request.args.get('id', 0))
    v = int(request.args.get('v', 0))
    if id <7 :
        return jsonify({'code': 500, 'msg': "这几个禁止操作!"})
    Dtable.query.filter(Dtable.id == id).update({'status':abs(v-1)})
    db.session.commit()
    return jsonify({'code': 200, 'msg': "操作成功!"})